package 字符串.反转字符串2;

/**
 * @author: wh(1835734390 @ qq.com)
 * @date: 2023/1/16 15:34
 * @description:
 * @version:
 */
public class Solution {
    public static void main(String[] args) {
        String s =  "abcdefghijk";
        int k = 2;
        System.out.println(reverseStr3(s, k));
    }


    public static String reverseStr(String s, int k) {
        int length = s.length();
        int i = 0,j= 0;
        String newStr = s;
        while (length >= 2*k){
            String s1 = reByStart(newStr, i, i + k-1);
            i += 2*k;
            length -= 2*k;
            newStr = s1;
        }
        if (length < k){
            String s1 = reByStart(newStr, s.length() - length, s.length() - 1);
            newStr = s1;
        }else {
            String s1 = reByStart(newStr, s.length()- length, s.length() - 1 - length + k);
            newStr = s1;
        }
        return newStr;
    }

    public static String reByStart(String str,int start,int end){
        char[] array = str.toCharArray();
        int left = start;
        int right = end;
        while (left < right){
            char tem = array[left];
            array[left] = array[right];
            array[right] = tem;
            left++;
            right--;
        }
        return String.valueOf(array);
    }


    //官方解法
    public static String reverseStr2(String s, int k) {
        int n = s.length();
        char[] arr = s.toCharArray();
        for (int i = 0; i < n; i += 2 * k) {
            reverse(arr, i, Math.min(i + k, n) - 1);
        }
        return new String(arr);
    }

    public static void reverse(char[] arr, int left, int right) {
        while (left < right) {
            char temp = arr[left];
            arr[left] = arr[right];
            arr[right] = temp;
            left++;
            right--;
        }
    }


    //使用StringBuilder
    public static String reverseStr3(String s, int k) {
        StringBuilder res = new StringBuilder();
        int index = 0;
        int length = s.length();
        while (index < length) {
            int end = Math.min(index + k, length);
            StringBuilder temp = new StringBuilder(s.substring(index, end));
            //前半部分反转，后半部分不反转  /与%的区别 前者取整 后者取余
            if ((index / k) % 2 == 0) res.append(temp.reverse());
            else res.append(temp);
            index = end;
        }
        return res.toString();
    }


























}
